package com.learn.utils;

import com.learn.pojo.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class HtmlParseUtil {
    //获取请求
    public static void main(String[] args) throws Exception {
        List<Content> contentList = parseJD("电饭锅");
        System.out.println(contentList);
    }

    public static List<Content> parseJD(String keywords)throws Exception{
        String url = "https://search.jd.com/Search?keyword=" + keywords;

        Document document = Jsoup.parse(new URL(url), 3000);

        List<Content> contentList = new ArrayList<>();


        Element j_goodsList = document.getElementById("J_goodsList");

        //System.out.println(j_goodsList);

        Elements lis = j_goodsList.getElementsByTag("li");

        for (Element li : lis) {

            Content content = new Content();
            String img = li.getElementsByTag("img").eq(0).attr("src");
             //String sourceDataLazyImg = li.getElementsByTag("img").attr("source-data-lazy-img");
            String price = li.getElementsByClass("p-price").eq(0).text();
            String name = li.getElementsByClass("p-name").eq(0).text();

            content.setImg(img);
            content.setPrice(price);
            content.setTitle(name);

            contentList.add(content);
        }

        return contentList;
    }

}
